<template>
  <BasicModal v-bind="$attrs"
              @register="registerModal"
              title="编辑头像"
              @ok="sub">
    <Spin :spinning="spinning">
      <Upload v-model:file-list="fileList"
              name="file"
              list-type="picture-card"
              class="photo-avatar-uploader"
              :show-upload-list="false"
              :action="uploadImgApi"
              :before-upload="beforeUpload"
              @change="handleChange">
        <img v-if="imageUrl"
             :src="imageUrl"
             alt="avatar" />
        <div v-else>
          <div class="ant-upload-text">点击上传</div>
        </div>
      </Upload>
    </Spin>
  </BasicModal>
</template>

<script lang="ts">
import { defineComponent, ref, computed, unref } from 'vue';
import { BasicForm } from '/@/components/Form/index';
import { throttle } from '/@/utils/throttle';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { Upload, Spin } from 'ant-design-vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { getAppEnvConfig } from '/@/utils/env';
import headerImg from '/@/assets/images/header.jpg';
import { userStore } from '/@/store/modules/user';
import { EditPhotoApi } from '/@/api/user/salesUser/index';
interface FileItem {
  uid: string;
  name?: string;
  status?: string;
  response?: string;
  url?: string;
  type?: string;
  size: number;
  originFileObj: any;
}

interface FileInfo {
  file: FileItem;
  fileList: FileItem[];
}
export default defineComponent({
  name: 'ActivityModal',
  components: {
    BasicModal,
    BasicForm,
    Upload,
    Spin,
  },
  setup() {
    const spinning = ref<boolean>(false);
    const { createMessage } = useMessage();
    // 图片APi
    const uploadImgApi = ref<string>(getAppEnvConfig().VITE_GLOB_API_URL + '/mini/getFileUrl');
    const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {});
    function handleSubmit() {
      try {
        userStore.getUserInfoState.avatar = unref(imageUrl);
        EditPhotoApi(userStore.getUserInfoState).then((res) => {
          if (res.code == 200) {
            createMessage.success('上传成功！');
            userStore.getUserInfoByIdAction(userStore.getUserInfoState.userId);
          }
        });
        closeModal();
      } finally {
        setModalProps({ confirmLoading: false });
      }
    }
    const sub = throttle(handleSubmit);
    const fileList = ref([]);
    const loading = ref<boolean>(false);
    const imageUrl = ref<string>('');
    const getUserInfo = computed(() => {
      const { avatar } = userStore.getUserInfoByIdState || {};
      return avatar;
    });
    if (getUserInfo.value) {
      if (getUserInfo.value.indexOf('http') !== -1) {
        imageUrl.value = getUserInfo.value;
      } else {
        imageUrl.value = headerImg;
      }
    } else {
      imageUrl.value = headerImg;
    }
    const handleChange = (info: FileInfo) => {
      if (info.file.status === 'uploading') {
        loading.value = true;
        return;
      }
      if (info.file.status === 'done') {
        const { code, data } = info.file.response;
        if (code == 200) {
          imageUrl.value = data[0];
        }
        // Get this url from response in real world.
        // getBase64(info.file.originFileObj, (base64Url: string) => {
        //   imageUrl.value = base64Url;
        //   loading.value = false;
        // });
      }
      if (info.file.status === 'error') {
        loading.value = false;
        createMessage.error('上传失败！');
      }
      spinning.value = false;
    };

    const beforeUpload = (file: FileItem) => {
      spinning.value = true;
      const isJpgOrPng =
        file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/JPG';
      if (!isJpgOrPng) {
        createMessage.error('上传图形格式只能上传：JPG、PNG、JPEG!');
      }
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        createMessage.error('图像必须小于5MB!');
      }
      return isJpgOrPng && isLt2M;
    };
    return {
      sub,
      registerModal,
      fileList,
      loading,
      imageUrl,
      handleChange,
      beforeUpload,
      uploadImgApi,
      headerImg,
      spinning,
    };
  },
});
</script>
<style lang="less" scoped>
:deep(.ant-spin-container) {
  height: 500px;
}
</style>
<style lang="less">
.photo-avatar-uploader {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 200px;
  height: 200px;
  transform: translate(-50%, -50%);
  .ant-upload {
    width: 100%;
    height: 100%;
    img {
      margin: 0 auto;
    }
  }
}
</style>
